package com.sunclyde.bbs.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain filterChain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		System.out.println("Call Me Now");
		String uri = request.getRequestURI();
		uri = uri.substring(uri.lastIndexOf("/"), uri.length());
		System.out.println(uri);

		HttpSession session = request.getSession();
		String method = (String) request.getParameter("method");
		System.out.println("method: " + method);

		if ("register".equals(method) && "/user.do".equals(uri)) {
			System.out.println(1 + ": " + uri);
			request.getRequestDispatcher(uri).forward(request, response);
			return;
		} else if ("login".equals(method) && "/user.do".equals(uri)) {
			System.out.println(2 + ": " + uri);
			request.getRequestDispatcher(uri).forward(request, response);
		} else {
			if (session.getAttribute("userId") == null) {
				System.out.println(3 + ": " + uri);
				request.getRequestDispatcher("/notLogin.do").forward(request,
						response);
				return;
			}
		}
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

}